using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Mes
{
    public static class HttpClientHelper
    {
        /// <summary>
        /// 基础API地址
        /// </summary>
        private const string BASE_API_URL = "http://10.223.8.10:8521/";

        /// <summary>
        /// 获取完整的API URL
        /// </summary>
        /// <param name="endpoint">API端点路径（建议以/开头，如：/api/Inspection/GetQueryCheck）</param>
        /// <returns>完整的API URL（避免出现双斜杠，如 https://localhost:7149/api/...）</returns>
        public static string GetApiUrl(string endpoint)
        {
            if (string.IsNullOrEmpty(endpoint))
                return BASE_API_URL;
            
            // 统一规范：endpoint 以/开头
            if (!endpoint.StartsWith("/"))
                endpoint = "/" + endpoint;
            
            // 拼接时避免出现 "//api" 的双斜杠
            var baseUrl = BASE_API_URL.EndsWith("/") ? BASE_API_URL.TrimEnd('/') : BASE_API_URL;
            return baseUrl + endpoint;
        }

        /// <summary>
        /// 获取基础API地址
        /// </summary>
        /// <returns>基础API地址</returns>
        public static string GetBaseApiUrl()
        {
            return BASE_API_URL;
        }

        /// <summary>
        /// Get/Post/Put/Delete(delete是通过url传值的方式)
        /// </summary>
        /// <param name="method">请求方式</param>
        /// <param name="url">请求地址</param>
        /// <param name="isAuthorzation">是否授权</param>
        /// <param name="content">参数内容</param>
        /// <returns></returns>
        public static async Task<string> ClientAsync(string method, string url, bool isAuthorzation = false, HttpContent content = null)
        {
            var result = "";
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    // 设置超时时间，避免长时间等待
                    client.Timeout = TimeSpan.FromSeconds(30);

                    if (isAuthorzation)
                    {
                        AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Bearer",login.CurrentToken);
                        client.DefaultRequestHeaders.Authorization = authentication;
                    }
                    HttpResponseMessage httpResponseMessage = null;

                    if (method.ToUpper() == "GET")
                    {
                        httpResponseMessage = await client.GetAsync(url);
                    }
                    else if (method.ToUpper() == "POST")
                    {
                        httpResponseMessage = await client.PostAsync(url, content);
                    }
                    else if (method.ToUpper() == "PUT")
                    {
                        httpResponseMessage = await client.PutAsync(url, content);
                    }
                    else if (method.ToUpper() == "DELETE")
                    {
                        httpResponseMessage = await client.DeleteAsync(url);
                    }
                    if (httpResponseMessage != null)
                    {
                        //判断请求是否成功 
                        if (httpResponseMessage.IsSuccessStatusCode)
                        {
                            //json字符串获取
                            string json = await httpResponseMessage.Content.ReadAsStringAsync();
                            result = json;
                        }
                        else
                        {
                            // 处理错误状态码
                            string errorContent = await httpResponseMessage.Content.ReadAsStringAsync();
                            // 返回格式化的JSON错误信息，而不是纯文本
                            result = JsonConvert.SerializeObject(new
                            {
                                Code = (int)httpResponseMessage.StatusCode,
                                Message = $"HTTP {(int)httpResponseMessage.StatusCode}: {httpResponseMessage.StatusCode} - {errorContent}"
                            });
                        }
                    }
                    else
                    {
                        result = JsonConvert.SerializeObject(new { Code = 500, Message = "请求失败，未收到响应" });
                    }
                }
            }
            catch (HttpRequestException ex)
            {
                // 处理HTTP请求异常
                string errorMessage = string.Format("HTTP请求异常: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    errorMessage += string.Format("\n内部异常: {0}", ex.InnerException.Message);
                }
                result = JsonConvert.SerializeObject(new { Code = 500, Message = errorMessage });
            }
            catch (TaskCanceledException ex)
            {
                // 处理请求超时
                result = JsonConvert.SerializeObject(new { Code = 408, Message = string.Format("请求超时: {0}", ex.Message) });
            }
            catch (Exception ex)
            {
                // 处理其他异常
                string errorMessage = string.Format("请求异常: {0}", ex.Message);
                if (ex.InnerException != null)
                {
                    errorMessage += string.Format("\n内部异常: {0}", ex.InnerException.Message);
                }
                result = JsonConvert.SerializeObject(new { Code = 500, Message = errorMessage });
            }
            return result;
        }

        /// <summary>
        /// delete(通过body方式传值)
        /// </summary>
        /// <param name="url">请求地址</param>
        /// <param name="isAuthorzation">是否授权</param>
        /// <param name="content">参数内容</param>
        /// <returns></returns>
        public static async Task<string> DeleteAsync(string url, bool isAuthorzation = false, HttpContent content = null)
        {
            var result = "";
            using (HttpClient client = new HttpClient())
            {
                if (isAuthorzation)
                {
                    AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Bearer",login.CurrentToken);
                    client.DefaultRequestHeaders.Authorization = authentication;
                }

                HttpRequestMessage httpRequestMessage = new HttpRequestMessage(HttpMethod.Delete, url);
                httpRequestMessage.Content = content;
                //发送请求
                HttpResponseMessage httpResponseMessage = client.SendAsync(httpRequestMessage).Result;
                //判断请求是否成功 
                if (httpResponseMessage.IsSuccessStatusCode)
                {
                    //json字符串获取
                    string json = await httpResponseMessage.Content.ReadAsStringAsync();
                    result = json;
                }
            }
            return result;
        }

        /// <summary>
        /// POST请求并返回泛型结果
        /// </summary>
        /// <typeparam name="T">返回类型</typeparam>
        /// <param name="url">请求地址</param>
        /// <param name="data">请求数据</param>
        /// <param name="isAuthorzation">是否授权</param>
        /// <returns>泛型结果</returns>
        public static async Task<T> PostAsync<T>(string url, object data, bool isAuthorzation = false)
        {
            try
            {
                // 序列化请求数据
                string jsonData = JsonConvert.SerializeObject(data);
                System.Diagnostics.Debug.WriteLine($"PostAsync<T> Request URL: {url}");
                System.Diagnostics.Debug.WriteLine($"PostAsync<T> Request Data: {jsonData}");

                var content = new StringContent(jsonData, Encoding.UTF8, "application/json");

                // 调用通用方法
                string result = await ClientAsync("POST", url, isAuthorzation, content);

                System.Diagnostics.Debug.WriteLine($"PostAsync<T> Raw Response: {result}");

                // 反序列化结果
                if (!string.IsNullOrEmpty(result))
                {
                    try
                    {
                        var deserializedResult = JsonConvert.DeserializeObject<T>(result);
                        System.Diagnostics.Debug.WriteLine($"PostAsync<T> Deserialized Result: {JsonConvert.SerializeObject(deserializedResult)}");
                        return deserializedResult;
                    }
                    catch (JsonException jsonEx)
                    {
                        System.Diagnostics.Debug.WriteLine($"PostAsync<T> JSON Deserialization Error: {jsonEx.Message}");
                        System.Diagnostics.Debug.WriteLine($"PostAsync<T> Failed to parse: {result}");
                        return default(T);
                    }
                }

                // 如果结果为空，记录并返回默认值
                System.Diagnostics.Debug.WriteLine($"PostAsync<T> Empty response received");
                return default(T);
            }
            catch (Exception ex)
            {
                // 记录错误并返回默认值
                System.Diagnostics.Debug.WriteLine($"PostAsync<T> error: {ex.Message}");
                System.Diagnostics.Debug.WriteLine($"PostAsync<T> Stack trace: {ex.StackTrace}");
                return default(T);
            }
        }

        /// <summary>
        /// GET 二进制内容（用于文件下载）
        /// </summary>
        public static async Task<byte[]> GetBytesAsync(string url, bool isAuthorzation = false)
        {
            try
            {
                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(60);
                    if (isAuthorzation)
                    {
                        AuthenticationHeaderValue authentication = new AuthenticationHeaderValue("Bearer", login.CurrentToken);
                        client.DefaultRequestHeaders.Authorization = authentication;
                    }
                    var resp = await client.GetAsync(url);
                    if (!resp.IsSuccessStatusCode)
                    {
                        // 返回null表示失败，由调用方处理提示
                        return null;
                    }
                    return await resp.Content.ReadAsByteArrayAsync();
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
